package com.example.mybaseapp.widget.my_circle_seekbar

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.example.mybaseapp.R
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.properties.Delegates

class MyCircleSeekBar: View {
    /**传入的刻度*/
//    private val points = mutableListOf(-6F,-3F,0F,3F,6F,9F,12F,15F,16F)
    private val points = mutableListOf<PointsData>()
    /**线的角度*/
//    private val lineDegrees = mutableListOf<Float>()
    private val halfCirclePaint = Paint()

    val circleUtil = CircleUtil()
    val drawUtil = DrawUtil(this,circleUtil)
    /**半圆的角度，这个是根据控件大小，动态获取的*/
    private var radius = 0f
    /**半圆的颜色*/
    private var halfCircleColor = 0
    /**半圆从哪个角度开始画起*/
    private var halfCircleStartAngle = 180f
    /**半圆的范围*/
    private var halfCircleSweepAngle = 180f



    /**线的颜色*/
    private var lineColor = 0
    /**选中的颜色*/
    private var lineSelectColor = 0


    /**
     * 半圆显示出来的范围
     */
    private val rect = RectF()

    /**圆心X*/
    private var centerX by Delegates.notNull<Float>()
    /**圆心Y*/
    private var centerY by Delegates.notNull<Float>()
    private val linePaint = Paint()
    private val lineRedPaint = Paint()
    /**最小刻度的角度差*/
    private var lineDegree by Delegates.notNull<Float>()

    private var touchStartX: Float = 0f
    private var touchStartY: Float = 0f
    private var touchDegree: Float = 0F

    private val pathPaint = Paint()


    constructor(context: Context) : super(context) {
        // 构造函数处理
        initView()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        // 构造函数处理，处理从 XML 布局文件中传入的属性
        initAttars(attrs)
        initView()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        // 构造函数处理，处理从 XML 布局文件中传入的属性和样式
        initAttars(attrs)
        initView()
    }

    private fun initAttars(attrs: AttributeSet) {
        // 从 AttributeSet 中获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCircleSeekBar)
        halfCircleColor = typedArray.getColor(R.styleable.MyCircleSeekBar_halfCircleColor, resources.getColor(R.color.half_circle_default_color,null))
        lineColor = typedArray.getColor(R.styleable.MyCircleSeekBar_lineColor, resources.getColor(R.color.line_default_Color,null))
        lineSelectColor = typedArray.getColor(R.styleable.MyCircleSeekBar_lineSelectColor, resources.getColor(R.color.line_select_default_Color,null))
        drawUtil.distanceFromEdge = typedArray.getDimension(R.styleable.MyCircleSeekBar_distanceFromEdge, resources.getDimension(R.dimen.dp_8))
        typedArray.recycle()
    }

    /**
     * 初始化各种参数
     */
    private fun initView() {
        halfCirclePaint.color = halfCircleColor
        halfCirclePaint.style = Paint.Style.FILL
        halfCirclePaint.isAntiAlias = true

        linePaint.apply {
            isAntiAlias = true//抗锯齿
            strokeWidth = 4f//笔的宽度
            isDither = true//启用抖动，有助于减少色带效应和锯齿。
            color = lineColor//颜色
            strokeCap = Paint.Cap.ROUND//设置画笔的端点为圆形
            textSize = context.resources.getDimension(R.dimen.sp_12)
            textAlign = Paint.Align.CENTER
        }
        lineRedPaint.apply {
            isAntiAlias = true//抗锯齿
            strokeWidth = 4f//笔的宽度
            isDither = true//启用抖动，有助于减少色带效应和锯齿。
            color = lineSelectColor//颜色
            strokeCap = Paint.Cap.ROUND//设置画笔的端点为圆形
            textSize = context.resources.getDimension(R.dimen.sp_12)
            textAlign = Paint.Align.CENTER
        }
        circleUtil.startDegree = drawUtil.selectDegree.toDouble()
        lineDegree = 15F
        circleUtil.errorDegreeRange = lineDegree/2
        Log.d("Fire", "initView: lineAngel=$lineDegree")
        getAllLinesAngel()

        pathPaint.apply {
            color = Color.RED
            style = Paint.Style.FILL
        }

    }

    private fun getAllLinesAngel() {
        for (n in 0 until points.size){
//            通过弧度来计算位置
            points[n].degree = 180 - n*lineDegree
        }
    }


    fun addPoints(mPoints: List<Int>){
        points.clear()
        for(d in mPoints){
            points.add(PointsData(d))
        }
        getAllLinesAngel()
        invalidate()
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)

        // 选择宽高中较小的值作为半圆形的半径
        radius = if (width < height) width / 2f else height / 2f
        centerX = width / 2f
        centerY = height.toFloat()
        drawUtil.centerX = centerX
        drawUtil.centerY = centerY
        drawUtil.radius = radius



        rect.set(0f, 0f, width.toFloat(), height.toFloat())
//        centerX = rect.centerX()
//        centerY = rect.bottom
        // 设置自定义 View 的尺寸
        setMeasuredDimension(width, height)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
//        canvas.clipRect(rect) // 裁剪出矩形范围

        if(points.size==0){
            return
        }
        drawUtil.drawableHalfCircle(canvas,halfCircleStartAngle,halfCircleSweepAngle,halfCirclePaint)
        drawUtil.drawableLine(canvas,points, touchDegree,lineRedPaint, linePaint)
        drawUtil.drawableSelectLine(canvas,touchDegree,this,pathPaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN ->{
                touchStartX = event.x
                touchStartY = event.y
                circleUtil.resetMoveState()//初始化移动差距
                if(circleUtil.isContainSelectLine(touchStartX,touchStartY,drawUtil.selectBottomX,drawUtil.selectTopX,drawUtil.selectBottomY,drawUtil.selectTopY)){
                    drawUtil.MotionEvent_Select_Line_ACTION_DOWN = true

                }else {
                    drawUtil.MotionEvent_Line_ACTION_DOWN = true
                }
            }
            MotionEvent.ACTION_MOVE -> {
                val x = event.x
                val y = event.y

                if(drawUtil.MotionEvent_Line_ACTION_DOWN){
                    drawUtil.MotionEvent_Line_ACTION_MOVE = true
                }else if(drawUtil.MotionEvent_Select_Line_ACTION_DOWN){
                    drawUtil.MotionEvent_Select_Line_ACTION_MOVE = true
                }

                // 计算手指按下位置和当前位置与圆心坐标形成的夹角
                touchDegree = circleUtil.calculateAngle1(x,y, centerX, centerY, touchStartX, touchStartY)
                println("onTouchEvent touchDegree=$touchDegree")

                // 限制夹角在 0~360 度之间
                if(touchDegree>180){
                    touchDegree %= 360
                }else if(touchDegree<-360){
                    touchDegree %= -360
                }
                println("onTouchEvent 转化之后的 $touchDegree")

                invalidate()
            }

            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP ->{
                if(drawUtil.MotionEvent_Line_ACTION_MOVE){
                    drawUtil.MotionEvent_Line_ACTION_UP = true
                    invalidate()
                }else if(drawUtil.MotionEvent_Select_Line_ACTION_MOVE){
                    drawUtil.MotionEvent_Select_Line_ACTION_UP = true
                    invalidate()
                }
            }
        }

        return true
    }

//显示的角度是0-halfCircleStartAngle

}